<?php

	require_once("gbif.general.php");

	class Occurrence extends General{

		public $basisOfRecordArray = array(
				"Fossil Specimen"
			,	"Living Specimen"
			,	"Human Observation"
			,	"Location"
			,	"Machine Observation"
			,	"Nomenclatural Checklist"
			,	"Occurrence"
			,	"Preserved Specimen"
			,	"Taxon"
		);
		
		public function validateOccurrenceData( $sheetIndex = 2 ) {
			if (!$this->fileOpen) $this->openExcel();

			$passed = true;
			$wk = $this->objPHPExcel->setActiveSheetIndex( $sheetIndex );

			$this->headerList = array(
					"globalUniqueIdentifier"
				,	"institutionCode"
				,	"collectionID"
				,	"collectionCode"
				,	"catalogNumber"
				,	"sex"
				,	"kingdom"
				,	"phylum"
				,	"class"
				,	"order"
				,	"family"
				,	"genus"
				,	"subgenus"
				,	"specificEpithet"
				,	"infraspecificEpithet"
				,	"scientificName"
				,	"scientificNameAuthorship"
				,	"scientificNameRank"
				,	"dateIdentified"
				,	"identifiedBy"
				,	"typeStatus"
				,	"continent"
				,	"waterBody"
				,	"country"
				,	"stateProvince"
				,	"locality"
				,	"decimalLatitude"
				,	"decimalLongitude"
				,	"coordinatePrecision"
				,	"minimumElevationInMeters"
				,	"maximumElevationInMeters"
				,	"minimumDepthInMeters"
				,	"maximumDepthInMeters"
				,	"basisOfRecord"
				,	"eventDate"
				,	"year"
				,	"month"
				,	"day"
				,	"habitat"
				,	"fieldNumber"
				,	"recordedBy"
				,	"collectionMethod"
				,	"associatedMedia"
				,	"eventRemarks"
				,	"DateLastModified"
			);


			$highestRow = $wk->getHighestRow();
			$highestColumn = $wk->getHighestColumn();
			$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);

			# Builds array but removes any blank rows
			for ($row = 1; $row <= $highestRow; ++$row) {
				
				$blankRow = true;				
				for ($col = 0; $col <= $highestColumnIndex; ++$col) {
					$value = $wk->getCellByColumnAndRow($col, $row)->getValue(); // Removed utf8_decode() for unicode compatibility. bko@GBIFS on 12 Dec 11.
					# Check that data do not contain control characters that break the XML transfer format (e.g. vertical tabs).  Remove if included.
					$value = str_replace("\x0B", "", $value);  //remove all vertical tabs in sender string
#ADD MORE CONDITIONS

					$this->sheetArray[$row][$col] = $value;
					if ($this->sheetArray[$row][$col] != "") {
						$blankRow = false;
					}
				}
				if ($blankRow) {
					unset($this->sheetArray[$row]);
				}
			}

			# Remove header row from array and set to local variable
			$this->header = array_shift($this->sheetArray);
			
			# Check for the presence and sequence of all column headers in order to generate the proper meta.xml file
			for($i=0; $i<=count($this->headerList); $i++) {
				if ($this->header[$i] != $this->headerList[$i]) {
					$this->addError("MandatoryElement", 203, sprintf("Header columns do not match '%s' != '%s'", $this->header[$i], $this->headerList[$i]) );
					$passed = false;
				}
			}

			for ($i=0; $i< count($this->sheetArray); $i++) {
				$row = $this->sheetArray[$i];

				# Mandatory elements are �globalUniqueIdentifier�, �institutionCode�, �collectionCode�, �collectionID�, �catalogueNumber�, �scientificName�, �basisOfRecord�. Check must be given to make sure that these fields are there for all records.
				$mandatoryArray = array(
						"0" => "globalUniqueIdentifier"
					,	"1" => "institutionCode"
					,	"2" => "collectionID"
					,	"3" => "collectionCode"
					,	"4" => "catalogNumber"
					,	"15" => "scientificName"
					,	"33" => "basisOfRecord"
				);

				foreach($mandatoryArray as $key => $value) {
#					print $key . $value . " $row[$key]<br>";
					if ($row[$key] == '') {
						$this->addError("MandatoryElement", 200, "$value not found on row: $i" );
						$passed = false;
					}
				}

				# Check that date elements are in the accepted DATE format as specified in the Metadata processing section above.
				
				# Geo-coordinates � requires decimal degrees and minutes.
/*				
				if (!is_float( $row[26]) ) {
					$this->addError("MandatoryElement", 202, "Coordinate: '$row[26]' is not a valid type on row: $i" );
					$passed = false;
				}
*/

				# depth and altitude (out of range, is 0)
				#29 30 31 32
				
				# basis of record � limited to members of BasisOfRecord vocabulary in Vocabulary Sheet.
				if (!in_array( $row[33], $this->basisOfRecordArray)) {
					$this->addError("MandatoryElement", 201, "BasicOfRecord: '$row[33]' is not a valid type on row: $i" );
					$passed = false;
				}
			}

			return( $passed );
		}

		public function writeOccurenceData( $outputFile ) {
			$fp = fopen($outputFile, 'w');
#			print_r($this->header);
			fputcsv($fp, $this->header);
			if(is_array($this->sheetArray)) {
			foreach ($this->sheetArray as $row) {
				fputcsv($fp, $row );
			}
			}
			fclose($fp);
		}
		
		public function generateOccurrenceDataMeta() {
			$this->xml = new XMLWriter();
			$this->xml->openMemory();
			$this->xml->startDocument('1.0', 'UTF-8');
			$this->xml->setIndent(4);
				$this->xml->startElement('archive');
				$this->xml->writeAttribute('xmlns', 'http://rs.tdwg.org/dwc/text/');

					$this->xml->startElement('core');
						$this->xml->writeAttribute('encoding', 'UTF-8');
						$this->xml->writeAttribute('linesTerminatedBy', $this->cr);
						$this->xml->writeAttribute('fieldsTerminatedBy', $this->delimiter);
						$this->xml->writeAttribute('fieldsEnclosedBy', '');
						$this->xml->writeAttribute('ignoreHeaderLines', '1');
						$this->xml->writeAttribute('rowType', 'http://rs.tdwg.org/dwc/terms/Taxon');
					$this->xml->endElement();
					
					$this->xml->startElement('files');
						$this->xml->writeElement('location', 'occurrence.csv');
					$this->xml->endElement();

					$this->xml->startElement('id');
						$this->xml->writeAttribute('index', 0);
					$this->xml->endElement();

					for($i=1; $i< count($this->headerList); $i++) {
						$this->xml->startElement('field');
							$this->xml->writeAttribute('index', $i);
							$this->xml->writeAttribute('term', 'http://rs.tdwg.org/dwc/terms/' . $this->headerList[$i]);
						$this->xml->endElement();
					}
					
				$this->xml->endElement();
			$this->xml->endDocument();
			return( $this->xml->outputMemory() );		
		}
	}

?>